package edu.gatech.teamrocket;

import java.sql.SQLException;
import java.util.List;

import com.j256.ormlite.dao.Dao;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import edu.gatech.teamrocket.models.Auth;
import edu.gatech.teamrocket.models.Category;
import edu.gatech.teamrocket.models.Task;

public class CategoryListActivity extends android.app.ListActivity implements OnClickListener {
	DewApplication app;
	Auth auth;
	
	private Dao<Category, Integer> categoryDao;
	private List<Category> categories;
	private ListAdapter categoryAdapter;
	private Button addButton;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (DewApplication) getApplicationContext();
		auth = app.getAuth();
		
		try {
			categoryDao = app.getHelper().getCategoryDao();
			categories = categoryDao.queryBuilder().where().eq("user_id", auth.getUser()).query();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
		setContentView(R.layout.categorylist);
		
		categoryAdapter = new ArrayAdapter<Category>(this, android.R.layout.simple_list_item_1, categories);
		setListAdapter(categoryAdapter);
		
		addButton = (Button) findViewById(R.id.addButton);
		addButton.setOnClickListener(this);
		
		registerForContextMenu(getListView());
	}
	
	/**
	 * Creates context menu for each item.
	 */
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.task_context_menu, menu);
	}
	
	/**
	 * Performs an action when a context item is selected.
	 */
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    Category category = categories.get((int) info.id);
	    switch (item.getItemId()) {
	        case R.id.menu_edit:
	        	Intent i = new Intent(getApplicationContext(), EditCategoryActivity.class);
	        	i.putExtra("CATEGORY_ID", category.getId());
	        	i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // remove this activity from history
				startActivity(i);
				finish();
	            return true;
	        case R.id.menu_delete:
				if (categories.size() == 1) {
					Toast.makeText(this, "You need at least one category!", Toast.LENGTH_SHORT).show();
				} else {
					try {
						Dao<Task, Integer> taskDao = app.getHelper().getTaskDao();
						List<Task> tasks = taskDao.queryBuilder().where().eq("user_id", auth.getUser()).and().eq("category_id", category.getId()).query();
						if (tasks.size() == 0) {
							categoryDao.delete(categories.get((int) info.id));
							categories.remove((int) info.id);
							setListAdapter(categoryAdapter);
							Toast.makeText(this, "Deleted!", Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(this, "You still have tasks in that category!", Toast.LENGTH_SHORT).show();
						}
					} catch (SQLException e) {
						throw new RuntimeException();
					}
				}
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	}

	/**
	 * ButtonBar listener that allows us to add a new category.
	 */
	public void onClick(View item) {
		Intent i;
		switch (item.getId()) {
		case R.id.addButton:
        	i = new Intent(getApplicationContext(), NewCategoryActivity.class);
        	i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // remove this activity from history
			startActivity(i);
			finish();
			break;
		}
	}
	
	/**
	 * Duplicate the edit button.
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Category category = categories.get((int) id);
    	Intent i = new Intent(getApplicationContext(), EditCategoryActivity.class);
    	i.putExtra("CATEGORY_ID", category.getId());
    	i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // remove this activity from history
		startActivity(i);
		finish();
	}
}
